﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UtilLib.Misc
{
	/// <summary>
	/// 两个对象之间的同名同类型属性赋值
	/// <para>注意：通过反射实现的，勿用于有性能要求的场合</para>
	/// </summary>
	public class PropertyCopy
	{
		public static void CopyProperties(object source, object destination)
		{
			var query = from sp in source.GetType().GetProperties()
						from dp in destination.GetType().GetProperties()
						where sp.Name == dp.Name
							&& dp.CanWrite
							&& dp.PropertyType.IsAssignableFrom(sp.PropertyType)
						select new { SourceProperty = sp, DestProperty = dp };

			foreach (var item in query)
			{
				var value = item.SourceProperty.GetValue(source);
				item.DestProperty.SetValue(destination, value);
			}
		}
	}
}
